/// <reference path="City.js" />
var request = require('request').defaults({
    json: true
});

var redis = require('redis');
var config = require('./../config.json');
var City = require('./City.js');



var q = require('q');
var extend = require('extend');
var User = function () {
    this.authentication = "";
    this.mail = "";
    this.phone = "";
    this.userName = "jigi"; //test only
    this.realName = "";
    this.corporation = "";
    this.department = "";
    this.avatar = "";

    this.authorizedDepartments = undefined; //可以分配的部门
    this.authorzedLevel = undefined; //可以分配的权限

    this.authorizedProjectList = undefined; //可拥有的权限项目
};

//用户的权限说明
User.authorDescription = [{
    name: "超级管理员",
    code: "Administrator",
    title: "超级管理员拥有最高的所有权限"
}, {
        name: "单位管理员",
        code: "CorpAdministrator",
        title: "单位管理员拥有本单位所有项目权限"
    }, {
        name: "部门管理员",
        code: "DepartAdministrator",
        title: "部门管理员可以操作所有本部门项目和人员"
    }, {
        name: "项目经理",
        code: "Manager",
        title: "项目经理只能查看和操作被授权的项目"
    }, {
        name: "普通用户",
        code: "User",
        title: "普通用户只能查看授权项目,无法上传或修改"
    }, {
        name: "业主用户",
        code: "Owner",
        title: "业主用户拥其公司发布的所有项目的所有权限"
    }];

//是否拥有用户管理权限
User.prototype.hasAdminPower = function () {
    var index1 = this.authentication.toLowerCase().indexOf('administrator');
    var index2 = this.authentication.toLowerCase().indexOf('owner');
    return (index1 >= 0 || index2 >= 0) ? true : false;
};
//是否是超级管理员
User.prototype.isAdministrator = function () {
    return this.authentication === 'Administrator';
};
User.prototype.hasReviewPower = function () {
    var user = this;
    if (user.authentication === "CorpAdministrator" || user.authentication === "Manager" || user.authentication === "DepartAdministrator") {
        return true;
    } else {
        return false;
    }
};

//获取关注的项目列表,是List<int>
User.prototype._getFavoriteProjectsList = function () {
    var defer = q.defer();
    var _this = this;
    request({
        method: 'get',
        url: config.adminBaseUrl + '/User/' + _this.userName + '/FavoriteProject'
    }, function (err, response, body) {
            if (!err && response.statusCode === 200) {
                defer.resolve(body);
            }
        });
    return defer.promise;
};

User.prototype.markProjectsChange = function () {
    var redisClient = redis.createClient();
    redisClient.set(config.redisNamespace + ":projectsChanged", 'yes');
    redisClient.quit();
};

//获取所有的有权限项目
User.prototype.getBackgroundProjects = function (typeCode) {
    var _this = this;
    var url = require('./../config.json').adminUrl;
    var defer = q.defer();
    var redisClient = redis.createClient();
    redisClient.get(config.redisNamespace + ":projectsChanged", function (err, reply) {
        var fromRedis = '1';
        if (err || !reply) {
            fromRedis = '1';
        } else {
            fromRedis = '0';
            redisClient.del(config.redisNamespace + ":projectsChanged");
        }
        request({
            method: 'get',
            url: config.authorUrl + '/backgroundProjects1/' + _this.userName + '/' + _this.uid + '/' + fromRedis
        }, function (err, response, body) {
                if (!err && response.statusCode === 200) {
                    if (typeof (body) === 'string') {
                        body = JSON.parse(body);
                    }
                    var cityList = City.parseProjectsToCityList(body, typeCode);
                    defer.resolve(cityList);
                } else {
                    console.log('fail to load!');
                }
            });
        redisClient.quit();
    });
    return defer.promise;
};

//获取关注的项目
User.prototype.getFavoriteProjects = function () {
    var _this = this;
    var defer = q.defer();
    q.all([_this.getBackgroundProjects(), _this._getFavoriteProjectsList()]).then(function (data) {
        var backPrjs = data[0],
            favorPrjs = data[1];
        var array = []; //存放关注prj的列表
        backPrjs.forEach(function (prj, arr, idex) {
            var id = favorPrjs.indexOf(prj.PrjId);
            if (id >= 0) {
                array.push(prj);
                Array.prototype.splice.call(favorPrjs, id, 1);
            }
        });
        defer.resolve(array);
    });
    return defer.promise;
};

//获取权限项目
User.prototype.getAuthorizedProjects = function () {
    var _this = this;
    var url = require('./../config.json').authorUrl;
    var defer = q.defer();
    request({
        method: 'get',
        url: config.authorUrl + '/authorizedProjects/' + _this.userName
    }, function (err, response, body) {
            if (!err && response.statusCode === 200) {
                if (typeof (body) === 'string') {
                    body = JSON.parse(body);
                }
                defer.resolve(body);
            } else {
                console.log('fail to load authorizedProjects!');
            }
        });
    return defer.promise;
};

//获取用户的账户申请者
User.prototype.getAppliers = function () {
    var _this = this;
    var defer = q.defer();
    var applierList = [];
    if (!_this.hasAdminPower) defer.resolve(applierList);
    request({
        method: "get",
        url: config.adminBaseUrl + "/user/" + _this.userName + "/applier"
    }, function (err, response, body) {
            if (!err && response.statusCode === 200) {
                if (typeof (body) === 'string') {
                    body = JSON.parse(body);
                }
                body.forEach(function (applier, index, arr) {
                    var person = extend(new User(), applier);
                    person.password = undefined; //不传送密码
                    person.department = _this.department; //默认同部门
                    person.corporation = _this.corporation; //默认同公司,且无法修改
                    person.authentication = "请指定权限"; //默认是普通用户
                    person.departmentList = _this.authorizedDepartments; //可以获得的部门
                    person.authorList = _this._parseAuthorList(_this.authorzedLevel); //可以获得的权限
                    applierList.push(person);
                });
                defer.resolve(applierList);
            } else {
                console.log('fail to load appliers!');
            }
        });
    return defer.promise;
};

User.prototype._parseAuthorList = function (list) {
    var arr = [];
    User.authorDescription.forEach(function (item) {
        if (list.indexOf(item.code) >= 0) {
            arr.push(item);
        }
    });
    return arr;
};

//处理一个申请者的信息
User.prototype.handleApplier = function (applier) {
    var _this = this;
    var defer = q.defer();

    try {
        applier.ApplierUserName = applier.userName;
        var authentication = User.authorDescription.filter(function (item) {
            return item.name === applier.authentication;
        })[0].code;
        applier.authentication = authentication; //从中文的权限表述换算成英文权限表述
    } catch (err) {
        applier.authentication = "User";
    }

    var url = config.adminBaseUrl + "/user/" + _this.userName + "/ApproveAccount";
    request({
        method: "post",
        url: url,
        json: JSON.stringify(applier)
    }, function (err, response, body) {
            if (!err && response.statusCode === 200) {
                var mailSend = require('./../service/mailSend.js');
                mailSend.notifyApplier({
                    reviewer: _this.realName,
                    applier: applier.realName,
                    accept: applier.accept
                }, applier.mail);
                defer.resolve(true);
            } else {
                defer.resolve(false);
            }
        });
    return defer.promise;
};

//更新用户的信息
User.prototype.updateInfo = function (data) {
    var _this = this;
    var url = require('./../config.json').adminBaseUrl + "/user/" + _this.userName + "/updateInfo";
    var defer = q.defer();
    request({
        method: 'post',
        url: url,
        json: JSON.stringify(data)
    }, function (err, response, body) {
            if (!err && response.statusCode === 200) {
                defer.resolve(body);
            } else {
                defer.resolve(false);
                console.log('fail to updateInfo!');
            }
        });
    return defer.promise;
};

//更改用户的密码
User.prototype.changePassword = function (postData) {
    var _this = this;
    var url = require('./../config.json').adminBaseUrl + "/user/" + _this.userName + "/changePassword";
    var defer = q.defer();
    request({
        method: 'post',
        url: url,
        json: JSON.stringify(postData)
    }, function (err, response, body) {
            if (!err && response.statusCode === 200) {
                defer.resolve(body);
            } else {
                defer.resolve(false);
                console.log('fail to changePassword!');
            }
        });
    return defer.promise;
};

//获取一个用户可以操作的下层用户
User.prototype.getAuthorizedUsers = function () {
    var _this = this;
    var defer = q.defer();
    var url = config.adminBaseUrl + "/user/" + _this.userName + "/authorizedUsers";
    request({
        method: 'get',
        url: url
    }, function (err, response, body) {
            if (!err && response.statusCode === 200) {
                body.forEach(function (u, index, array) {
                    var user = extend(new User(), u);
                    user.authentication = User.authorDescription.filter(function (item) {
                        //匹配code同authentication相同的item
                        return item.code === user.authentication;
                    })[0];
                    user.authorList = _this._parseAuthorList(_this.authorzedLevel); //可以获得的权限
                    //重新赋值给array
                    body[index] = user;
                });
                defer.resolve(body);
            } else {
                defer.resolve(false);
                console.log('fail to getAuthorizedUsers!');
            }
        });
    return defer.promise;
};


//更新某个用户的权限项目
User.prototype.updateAuthorizedProjectList = function () {
    var _this = this;
    var url = config.adminBaseUrl + "/AuthorizedProjects/" + _this.userName;
    var defer = q.defer();
    request({
        method: 'post',
        url: url,
        json: JSON.stringify(_this.authorizedProjectList)
    }, function (err, res, body) {
            if (!err && res.statusCode === 200) {
                defer.resolve(body);
            } else {
                defer.resolve(false);
            }
        });

    return defer.promise;
};

//解冻 or 冻结一个用户
User.prototype.freezeUser = function (user) {
    var _this = this;
    var url = config.adminBaseUrl + "/user/" + _this.userName + "/freezeUser";
    var defer = q.defer();
    request({
        method: 'post',
        url: url,
        json: JSON.stringify(user)
    }, function (err, res, body) {
            if (!err && res.statusCode === 200) {
                defer.resolve(body);
            } else {
                defer.resolve(false);
            }
        });
    return defer.promise;
};

User.prototype.updateUserAuthorizedProjectList = function (data) {
    var _this = this;
    var url = config.adminBaseUrl + "/user/" + _this.userName + "/updateUserAuthorizedProjectList";
    var defer = q.defer();
    request({
        method: 'post',
        url: url,
        json: JSON.stringify(data)
    }, function (err, res, body) {
            if (!err && res.statusCode === 200) {
                defer.resolve(body);
            } else {
                defer.resolve(false);
            }
        });
    return defer.promise;
};

User.prototype.changeUserAuthentication = function (data) {
    var _this = this;
    var url = config.adminBaseUrl + "/user/" + _this.userName + "/changeUserAuthentication";
    var defer = q.defer();
    request({
        method: 'post',
        url: url,
        json: JSON.stringify(data)
    }, function (err, res, body) {
            if (!err && res.statusCode === 200) {
                defer.resolve(body);
            } else {
                defer.resolve(false);
            }
        });
    return defer.promise;
};

User.prototype.getReviewProjectList = function () {
    var _this = this;
    var url = config.adminBaseUrl + "/user/" + _this.userName + "/needReviewProjects";
    var defer = q.defer();
    request({
        method: 'get',
        url: url
    }, function (err, res, body) {
            if (!err && res.statusCode === 200) {
                defer.resolve(body);
            } else {
                defer.resolve(false);
            }
        });
    return defer.promise;
};

//用户操作,审核/拒绝一个项目
User.prototype.reviewProject = function (params) {
    var _this = this;
    var url = config.adminBaseUrl + "/user/" + _this.userName + "/ReviewProject";
    var defer = q.defer();
    request({
        method: 'post',
        url: url,
        json: JSON.stringify(params)
    }, function (err, res, body) {
            if (!err && res.statusCode === 200) {
                defer.resolve(true);
            } else {
                defer.reject(false);
            }
        });
    return defer.promise;
};

module.exports = User;
